<?php


namespace app\common\model;


use app\common\lib\ZhyxMongo;
use app\common\model\search\ProjectSearch;
use app\common\utils\Questions;
use catchAdmin\permissions\model\DataRangScopeTrait;
use catcher\base\CatchModel;
use catcher\CatchQuery;
use catcher\Tree;
use think\facade\Db;
use think\Paginator;

class Project extends BaseModel
{

    use ProjectSearch;


    protected $name = "project";

    // 设置字段信息

    protected $type = [
        'status' => 'integer',
        'creator_id' => 'integer',
        'parentId' => 'string',
        'deleted_at' => 'integer',
        'created_at' => 'integer',
        'updated_at' => 'integer'
    ];


    public function setSurveyAttr($value)
    {
        if (is_string($value)) {
            $value = json_decode($value, true);
        }
        return Questions::getQuestionChartType($value);
    }

    public function setDeptListAttr($value)
    {
        if (is_string($value)) {
            return json_decode($value, true);
        }
        return $value;
    }

    public function setDiseaseAttr($value)
    {
        if (is_string($value)) {
            return json_decode($value, true);
        }
        return $value;
    }


    //protected $jsonAssoc = true;


    public function incNumber(string $projectId, string $fieldName, $session, int $step = 1)
    {
        $options = $session ? ['session' => $session] : [];

        //$result = $this->where("projectId", "=", $projectId)->inc($fieldName)->update();
        ZhyxMongo::getInstance()->setCollection($this->name)->updateOne(["projectId" => $projectId], ['$inc' => [$fieldName => 1]], $options);


    }

    public function decNumber(string $projectId, string $fieldName, $session = [], int $step = 1)
    {
        $options = $session ? ['session' => $session] : [];
        ZhyxMongo::getInstance()->setCollection($this->name)->updateOne(["projectId" => $projectId], ['$inc' => [$fieldName => -1]], $options);


    }

    /**
     * 获取问卷/文件夹信息
     * @param string $projectId
     */
    public function getProjectInfo(string $projectId)
    {
        return $this->where("projectId", "=", $projectId)->find();
    }

    public function getLists($userIds, $deptIds, $isShowAllData = false)
    {


        $param = request()->except(['limit', 'page']);

        $parentId = $param["parentId"] ?? "0";
        $map1 = [];
        $result = $this->where("deleted_at", "=", 0);
        if (empty($userIds) && empty($deptIds)) {
            $result = $result->whereOr(function ($query) use ($parentId) {
                $query->where("parentId", "=", $parentId)->where("mode", "=", "survey");
            });
            if ($parentId === "0") {
                $result = $result->whereOr([["mode", "=", "folder"], ["parentId", "=", "0"]]);
            }
        } else {
            if (!empty($deptIds)) {
                $map1[] = ["dept_list.dept_id", "in", $deptIds];
            }
            if (!empty($deptIds)) {
                $result = $result->whereOr(function ($query) use ($parentId, $deptIds) {
                    $query->where("parentId", "=", (string)$parentId);
                    $query->where("dept_list.dept_id", "in", $deptIds);
                });
                if ($parentId === "0") {
                    $projectIds = $this->where($map1)->where("creator_id", "<>", request()->user()->id)->where("mode", "=", "survey")->where("parentId", "<>", "0")->column("parentId");
                    //获取所有包含的问卷ID反推回文件夹
                    if (!empty($projectIds)) {
                        $result = $result->whereOr('projectId', 'in', $projectIds);
                    }
                }
            }
            if (!empty($userIds)) {
                $result = $result->whereOr(function ($query) use ($parentId) {
                    $query->where("parentId", "=", (string)$parentId);
                    $query->where("creator_id", "=", request()->user()->id);

                });
            }
            if ($parentId === "0") {
                $result = $result->whereOr(function ($query) {
                    $query->where([["mode", "=", "folder"], ["creator_id", "=", request()->user()->id]]);
                });
            }

        }
        //获取适用部门
        if ($isShowAllData) {
            return $result->order(["sort_no" => 1, "created_at" => -1])->select();
        }
        return $result->order(["sort_no" => 1, "created_at" => -1])->paginate($this->pageLimit);
    }

    public function getListToTree($userIds, $deptIds)
    {

        $match = [];
        $match[] = ["status", "=", 1];
        $result = $this->mongoSearch();
        if (!empty($userIds)) {
            $match[] = ["creator_id", "in", $userIds];
            $result = $result->whereOr("creator_id", "in", $userIds);

        }
        if (!empty($deptIds)) {
            $result = $result->where(function ($query) use ($deptIds) {
                $query->whereOr([["dept_list.dept_id", "in", $deptIds], ["creator_id", "=", request()->user()->id]]);
            });
            $match[] = ["dept_list.dept_id", "in", $deptIds];
            $match[] = ["creator_id", "=", request()->user()->id];
        }
        $allSurvey = $this->mongoSearch()->whereOr($match)->field(["id", "parentId", "name", "mode", "projectId", "survey_type"])->where([["mode", "=", "survey"]])->order(["created_at" => -1])->select();
        $projectIds = [];
        foreach ($allSurvey as $k => $v) {
            if ($v["parentId"] !== "0") {
                $projectIds[] = $v["parentId"];
            }
        }
        $allFolder = [];
        if (!empty($projectIds)) {
            $allFolder = $this->mongoSearch()->where("projectId", "in", $projectIds)->where([["status", "=", 1]])->where([["mode", "=", "folder"]])->field(["id", "parentId", "name", "mode", "projectId", "survey_type"])->order(["created_at" => -1])->select();
        }
        $resultRnd = [];

        if (!empty($allFolder)) {
            foreach ($allFolder->toArray() as $k => $v) {
                $resultRnd[$v["projectId"]] = $v;
            }
        }
        if (!empty($resultRnd) && !empty($allSurvey)) {
            foreach ($allSurvey->toArray() as $k => $v) {
                if ($v["parentId"] != "0") {
                    $resultRnd[$v["parentId"]]["children"][] = $v;
                } else {
                    $resultRnd[] = $v;
                }
            }
            return array_values($resultRnd);
        }
        return $allSurvey;
    }

    /**
     * 患者端获取满意度列表
     * @param array $param
     * @return Paginator
     */
    public function getMydDatas(array $param): Paginator
    {
        if ($param['personnelType'] == 1) {
            $where['personnelType'] = (int)$param['personnelType'];
            $where['classification'] = (int)$param['classification'] ?? '';
//            isset($param['classification']) && !empty($param['classification']) ? $where['classification'] = (int)$param['classification'] : '';
        } else {
            $where['personnelType'] = (int)$param['personnelType'];
        }
        $where['isopen'] = 1;
        $where['status'] = 1;
        return $this->where('status', '<>', 0)
            ->where($where)
            ->field('id,name,projectId')
            ->order('created_at', 'desc')
            ->paginate($this->pageLimit);
    }

}